package com.ts.controller.User;

import com.ts.dto.UserLoginDTO;
import com.ts.service.user.UserService;
import com.ts.constant.JwtClaimsConstant;
import com.ts.entity.User;
import com.ts.properties.JwtProperties;
import com.ts.result.Result;
import com.ts.utils.JwtUtil;
import com.ts.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户登录接口", description = "用户登录使用")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录")
    public Result<UserLoginVO> getUser(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        //先查数据库，异常会在数据库处理
        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        //构建VO对象
        UserLoginVO loginVO = UserLoginVO
                .builder()
                .userId(user.getUserId())
                .userName(user.getUserName())
                .token(token)
                .build();

        return Result.success(loginVO);
    }
}
